package com.xauto.pioneer.appuser.activity.mine.receipt;

import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.BaseActivity;
import com.xauto.pioneer.appuser.adapter.ApplyCarReceiptAdapter;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.interfaces.MemberCallBack;
import com.xauto.pioneer.appuser.model.CarReceiptableInfo;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.model.Member;
import com.xauto.pioneer.appuser.util.DataCheckUtil;
import com.xauto.pioneer.appuser.util.DataLoadUtil;
import com.xauto.pioneer.appuser.util.ToastUtil;
import com.xauto.pioneer.appuser.view.TopBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/5/25.
 */

public class ApplyCarReceiptActivity extends BaseActivity {
    @Bind(R.id.topBar_applycarreceipt)
    TopBar topBar_applycarreceipt;
//    @Bind(R.id.list_applycarreceipt)
//    PullToRefreshListView pullToRefreshListView;
    @Bind(R.id.list_applycarreceipt)
    ListView listView;
    @Bind(R.id.tv_applycarreceipt_submit)
    TextView tv_applycarreceipt_submit;
    @Bind(R.id.tv_applycarreceipt_total)
    TextView tv_applycarreceipt_total;
//    private List<HashMap<String,Object>> list;
    private List<HashMap<String,Object>> infoList;
//    HashMap<String, Object> map;
    HashMap<String, Object> infoMap;
    CarReceiptableInfo info;
    private List<String> listStr;
    ApplyCarReceiptAdapter adapter;

    Member member;
    /**是否全选*/
    boolean ifAllTrue = false;
    @Override
    protected int getContentView() {
        return R.layout.ac_applycarreceipt;
    }

    @Override
    protected void initView() {
        topBar_applycarreceipt.showView(TopBar.LEFT_IMAGE_BTN, TopBar.TITLE,TopBar.RIGHT_TV_BTN);
        topBar_applycarreceipt.setImage(TopBar.LEFT_IMAGE_BTN, R.mipmap.ic_common_left);
        if(ifAllTrue){
            topBar_applycarreceipt.setText(TopBar.RIGHT_TV_BTN, "取消全选");
        }else{
            topBar_applycarreceipt.setText(TopBar.RIGHT_TV_BTN, "全选");
        }
        topBar_applycarreceipt.setText(TopBar.TITLE, "租车订单");
        topBar_applycarreceipt.setLeftOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        topBar_applycarreceipt.setRightOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listStr.clear();
                JSONObject object = null;
                try {

                    if(ifAllTrue){
                        for(int i=0;i<infoList.size();i++){
                            infoList.get(i).put("boolean", false);
                        }
                        ifAllTrue = false;
                        topBar_applycarreceipt.setText(TopBar.RIGHT_TV_BTN, "全选");
                    }else{
                        for(int i=0;i<infoList.size();i++){
                            infoList.get(i).put("boolean", true);
                            object = new JSONObject(infoList.get(i).get("obj").toString());
                            listStr.add(object.getString("car_order_id"));
                        }
                        ifAllTrue = true;
                        topBar_applycarreceipt.setText(TopBar.RIGHT_TV_BTN, "取消全选");
                        getReceiptsCount(listStr);
                    }
                    adapter.notifyDataSetChanged();
                    Log.e("tag","已选择了:" + listStr.size() + "项");


                }catch (Exception e){

                }


            }
        });

        listView.setDividerHeight(3);
    }
    @OnClick({R.id.tv_applycarreceipt_submit})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.tv_applycarreceipt_submit:
                ifAllTrue = false;
                topBar_applycarreceipt.setText(TopBar.RIGHT_TV_BTN, "全选");
                if(listStr.size()>0){
                    if(member.member_receipt_info.user_receipt_state .equals("1")){
                        submitApplyReceipt(listStr);
                    }else{
                        startActivity(new Intent(mContext,ReceiptInputActivity.class));
                    }
                }else{
                    ToastUtil.showShort(mContext,"请至少选择一个订单");
                }

                break;
        }
    }
    @Override
    protected void initData() {
        getCarReceiptableList();
        listStr = new ArrayList<String>();
        infoList = new ArrayList<HashMap<String,Object>>();
        member = DataCheckUtil.getMemberObj(mContext);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //刷新页面
        DataLoadUtil.refreshMemberData(mContext, new MemberCallBack() {
            @Override
            public void getMember(Member m) {
                member = m;
            }
        });
    }

    void refreshData(){
        adapter = new ApplyCarReceiptAdapter(this,infoList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                ApplyCarReceiptAdapter.ViewCache viewCache = (ApplyCarReceiptAdapter.ViewCache) view.getTag();
                viewCache.cb_applycarreceipt.toggle();
                infoList.get(position).put("boolean", viewCache.cb_applycarreceipt.isChecked());
                adapter.notifyDataSetChanged();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(infoList.get(position).get("obj").toString());

                if(viewCache.cb_applycarreceipt.isChecked()){//被选中状态
                    Log.e("tag","check = "+infoList.get(position).get("obj").toString());
                        listStr.add(jsonObject.getString("car_order_id"));
                }else    {                       //从选中状态转化为未选中
                        listStr.remove(jsonObject.getString("car_order_id"));
                }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.e("tag","已选择了:"+listStr.size()+"项"+listStr.toString());
                if(listStr.size()>0){
                    getReceiptsCount(listStr);
                }
            }
        });
        adapter.notifyDataSetChanged();
    }
    /**
     * 获取车辆可开票订单列表
     * */
    private void getCarReceiptableList(){
        new LHttpLib().getCarReceiptableList(mContext, memberId, new BaseLHttpHandler(mContext, true, true) {
                    @Override
                    public void onSuccess(JSONStatus jsonStatus) {
                        super.onSuccess(jsonStatus);
                        JSONArray jsonArray = jsonStatus.data.optJSONArray("member_receipt_List");
                        if(jsonArray!=null&&jsonArray.length()>0){
                            for (int i = 0;i<jsonArray.length();i++){
                                infoMap = new HashMap<String, Object>();
                                info = new CarReceiptableInfo().parse(jsonArray.optJSONObject(i));
                                infoMap.put("obj",jsonArray.optJSONObject(i));
                                infoMap.put("boolean", false);//初始化为未选
                                infoList.add(infoMap);
                            }
                        }
                        refreshData();
                    }
                });
    }

    /**
     * 显示无数据页面
     */
    private void showNoDataView(){
        View emptyView = LayoutInflater.from(mContext).inflate(R.layout.layout_listview_empty, null);
        ((TextView) emptyView.findViewById(R.id.tvEmptyNotice)).setText("暂无订单");
        ((ViewGroup)listView.getParent()).addView(emptyView);
        listView.setEmptyView(emptyView);
    }
    /**
     * 获取可开票总和
     */
    private void getReceiptsCount(List<String>  list){
        JSONArray arry=new JSONArray();
        for (int i=0;i<list.size();i++){
            arry.put(list.get(i));
        }
        new LHttpLib().getReceiptsCount(mContext,memberId,arry,new BaseLHttpHandler(mContext,true,true){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                tv_applycarreceipt_total.setText("费用总计："+jsonStatus.data.optString("amount_format")+"元");
            }
        });
    }
    /**
     * 提交选中开票数据
     */
    private void submitApplyReceipt(List<String>  list){
        JSONArray arry=new JSONArray();
        for (int i=0;i<list.size();i++){
            arry.put(list.get(i));
        }
        new LHttpLib().submitApplyReceipt(mContext,memberId,arry,new BaseLHttpHandler(mContext,true,true){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                Intent intent = new Intent(mContext,ApplyReceiptInfoActivity.class);
                intent.putExtra("entity",jsonStatus.data.toString());
                startActivity(intent);
            }
        });
    }

}
